import Time from './Time';

/**
 * 提供 sessionStorage 操作
 * 提供 localStorage 操作
 * Set(key, value) 设置key值
 * Get(key) 获取指定key
 * Remove(key) 删除指定key
 * Clear() 清除所有session
 *
 */
class Session {

  // private Storage: any = sessionStorage;
  private Storage: any;

  public constructor(v: any = localStorage) {
    this.Storage = v;
  }

  /**
   *
   * 设置session值
   * @param key string 键
   * @param Val any 值
   * @param Expire number 过去时间
   *
   */
  public Set(key: string, val: any, expire: number = 0): void {
    if (expire > 0) { // 如果过去时间大于0
      expire = Time.TimeStamp() + expire;
    }
    const v = {expire, data: val};
    this.Storage.setItem(key, JSON.stringify(v));
  }

  /**
   *
   * 根据key键获取session值
   * @param key string 键
   * @return any
   *
   */
  public Get(key: string): any {
    const v = this.Storage.getItem(key);
    if (v == null) {
      return null;
    }
    const res = JSON.parse(v);
    if (res.expire > 0 && res.expire < Time.TimeStamp()) {
      this.Remove(key); // 删除已过期的信息
      return null;
    }
    return res.data;
  }

  /**
   *
   * 根据key删除session信息
   * @param key string 键
   *
   */
  public Remove(key: string): void {
    this.Storage.removeItem(key);
  }

  /**
   *
   * 清除所有session信息
   *
   */
  public Clear(): void {
    this.Storage.clear();
  }

}

export default Session;
